package com.fuqi.android.zhongcai.utils.pay.alipay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.fuqi.framework.gson.GsonHelper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Alipay {

	/** 支付宝支付业务：入参app_id */
	public static final String APPID = "2016081801767441";

	/** 支付宝账户登录授权业务：入参pid值 */
	public static final String PID = "2088421543631810";
	/** 支付宝账户登录授权业务：入参target_id值 */
	public static final String TARGET_ID = "guozheng.wang@jinchencp.com";

	/** 商户私钥，pkcs8格式 */
	public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMtPiD6UyiT1ALmBswr9TqfuBO4WBnzRdsqQYektqflp90tMXCC+wByD/zaSsRB6NUhzkLdxCU6GG9gl+6nfWz8GUrnzEMdvksL/VtinMvWze+g8lL5eWqWMa6wqyiiglbKFTJbYkYTMQIia+j7ZDuNTtmkLK+PBXWidVbKeUWfXAgMBAAECgYB3ZTp2vfxEXdlSF7fkkUOa3O3qP+cJcB1Z8hZ90IJMZY2Dm9FSrZK2bFH5Y4Y2Tf5ykOOAxxIXGizJ7+xuIyw6twMlxNJ4VqQZDxNscsQXxuUE8zcSUVh5dUf2K1jBDVD3NjXSi9rclLP8WVN9AwLCPVij52cQH6TUl4EhA2U5cQJBAPfngMmf5DQ9SgjuchIqaOAmO/xpnWEy/DYAQqo6ltEYqeq/h++VkYaqxYXA9S2NCzb7Bxd6iJl+qer//Cvbx7kCQQDR8zkpfhpwdRAcvN2oZIE7XD7j5AbCRQyuSM0FddGPFmjFddG1/YYYbG29qBZ7i0f4sBEMW21gXMcdhT+KKFQPAkAZG/uxcF5+5A5RpUUsjdsdiQHeaRwlsjJVjeUytMh92U+slUXBgJbC2x0ylP7AZF7UbMylFiYr1eaEBPWXw6URAkBIgW/nRXaKCdODqTH/mp4KywOpHjG7W69SbS/ox9SUTs/mCZdf+2sY+jE4A1moVuSHHP72Pojac5AMQN09sEm/AkEAoHGmktYz+V/95f/wuxxJp02ur1/FOuoEZqQRQSwjxsiuAKRW1tnGDrW+Im0gKCgZGojPFhFsfiJ6OLZbl66k9Q==";

	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_AUTH_FLAG = 2;
	private static AlipayListener alipayListener;

	@SuppressLint("HandlerLeak")
	private static Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				// PayResult payResult = new PayResult((Map<String, String>)
				// msg.obj);

				String payResult = msg.obj.toString().substring(msg.obj.toString().indexOf("{\"code\":"),
						msg.obj.toString().indexOf(",\"sign\""));
				AlipayResult alipayResult = GsonHelper.getDeserializer().fromJson(payResult, AlipayResult.class);

				// 判断code 为10000则代表支付成功
				if (TextUtils.equals(alipayResult.getCode(), "10000")) {
					// 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
					if (alipayListener != null) {
						alipayListener.alipaySuccess(alipayResult.getTotalAmount());
					}
				} else {
					// 该笔订单真实的支付结果，需要依赖服务端的异步通知。
					if (alipayListener != null) {
						alipayListener.alipayFailure();
					}
				}
				
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 * 支付宝支付业务
	 * 
	 * @param v
	 */
	public static void pay(final Activity activity, String price, String tradeNo, String intro) {

		if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA_PRIVATE)) {
			new AlertDialog.Builder(activity).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {
							//
							activity.finish();
						}
					}).show();
			return;
		}

		/**
		 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
		 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
		 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
		 * 
		 * orderInfo的获取必须来自服务端；
		 */
		Map<String, String> params = buildOrderParamMap(price, tradeNo, intro);
		String orderParam = buildOrderParam(params);
		String sign = getSign(params, RSA_PRIVATE);
		final String orderInfo = orderParam + "&" + sign;
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask alipay = new PayTask(activity);
				String result = alipay.pay(orderInfo, false);
				Log.i("msp", result.toString());

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * 构造支付订单参数列表
	 * 
	 * @param price
	 * @param tradeNo
	 * @param intro
	 * @return
	 */
	public static Map<String, String> buildOrderParamMap(String price, String tradeNo, String intro) {
		Map<String, String> keyValues = new HashMap<String, String>();

		keyValues.put("app_id", APPID);

		keyValues.put("biz_content",
				"{\"timeout_express\":\"90m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"" + price
						+ "\",\"subject\":\"" + intro + "\",\"body\":\"" + intro + "\",\"out_trade_no\":\"" + tradeNo
						+ "\"}");

//		keyValues.put("notify_url", HttpURL.NOTIFY_URL);

		keyValues.put("charset", "utf-8");

		keyValues.put("method", "alipay.trade.app.pay");

		keyValues.put("sign_type", "RSA");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		keyValues.put("timestamp", sdf.format(calendar.getTime()));

		keyValues.put("version", "1.0");

		return keyValues;
	}

	/**
	 * 构造支付订单参数信息
	 * 
	 * @param map
	 *            支付订单参数
	 * @return
	 */
	public static String buildOrderParam(Map<String, String> map) {
		List<String> keys = new ArrayList<String>(map.keySet());

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			sb.append(buildKeyValue(key, value, true));
			sb.append("&");
		}

		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		sb.append(buildKeyValue(tailKey, tailValue, true));

		return sb.toString();
	}

	/**
	 * 拼接键值对
	 * 
	 * @param key
	 * @param value
	 * @param isEncode
	 * @return
	 */
	private static String buildKeyValue(String key, String value, boolean isEncode) {
		StringBuilder sb = new StringBuilder();
		sb.append(key);
		sb.append("=");
		if (isEncode) {
			try {
				sb.append(URLEncoder.encode(value, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				sb.append(value);
			}
		} else {
			sb.append(value);
		}
		return sb.toString();
	}

	/**
	 * 对支付参数信息进行签名
	 * 
	 * @param map
	 *            待签名授权信息
	 * 
	 * @return
	 */
	public static String getSign(Map<String, String> map, String rsaKey) {
		List<String> keys = new ArrayList<String>(map.keySet());
		// key排序
		Collections.sort(keys);

		StringBuilder authInfo = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			authInfo.append(buildKeyValue(key, value, false));
			authInfo.append("&");
		}

		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		authInfo.append(buildKeyValue(tailKey, tailValue, false));

		String oriSign = SignUtils.sign(authInfo.toString(), rsaKey);
		String encodedSign = "";

		try {
			encodedSign = URLEncoder.encode(oriSign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "sign=" + encodedSign;
	}

//	public static void gotoPay(final Activity activity, final String money, final String flag,
//			final CircularProgress circularProgress) {
//		setAlipayListener((AlipayListener) activity);
//		Map<String, String> param = new HashMap<String, String>();
//		param.put("USER_ID", ToolUtils.getXmlData(activity, "userid"));
//		param.put("MONEY", money);
//		param.put("FLAG", flag);
//		HttpClient.get(HttpURL.ORDER_NO_URL, param, new HttpResponseHandler() {
//			@Override
//			public void onSuccess(String body) {
//
//				LogUtils.i("dialog pay body: " + body);
//				OrderNoResult orderNoResult = GsonHelper.getDeserializer().fromJson(body, OrderNoResult.class);
//				if ("00".equals(orderNoResult.getCode())) {
//					String intro = "";
//					if (flag.equals(Constants.PAY_TYPE_CHONG_ZHI)) {
//						intro = "充值钻石";
//					} else if (flag.equals(Constants.PAY_TYPE_DA_SHANG)) {
//						intro = "打赏";
//					} else {
//						intro = "未知";
//					}
//					pay(activity, money, orderNoResult.getOrderNo(), intro);
//
//				} else {
//
//					ActivityUtils.toast("获取订单号失败");
//				}
//
//				circularProgress.setVisibility(View.GONE);
//			}
//
//			@Override
//			public void onFailure(Request request, IOException e) {
//
//				ActivityUtils.toast("获取订单号失败");
//				circularProgress.setVisibility(View.GONE);
//			}
//		}, 0);
//	}

	
	

	public static void setAlipayListener(AlipayListener alipayListenerParam) {
		  alipayListener = alipayListenerParam;
	}



	public interface AlipayListener {

		public void getOrderNoSuccess();

		public void getOrderNoFailure();

		public void alipaySuccess(String totalAmount);

		public void alipayFailure();

	}

}
